<script lang="ts" setup>
import { ref, reactive, onMounted, nextTick } from 'vue';
import { CustomMouseMenu } from '@/plugins/directive/contextmenu';
import { ElMessageBox, ElMessage } from 'element-plus';
import useStore from '@/store';
import { LicenseEnum } from '@/enums/licence';
import { props } from './employee';
import { WindowType } from '@/types/global/window';
defineOptions({ name: 'Employee' });
defineProps(props);
const totalCount = ref(0);
const loading = ref(true);
const organizationLoading = ref(true);
const daterange = ref('');
const employees = ref(null);
const organizations = ref(null);
const educations = ref(null);
const employeeStatuss = ref(null);
const currentRow = ref(null);
const treeRef = ref(null);
const tableRef = ref(null);
const params = reactive({
  pageIndex: 1,
  pageSize: 20,
  query: {
    organizationId: null,
    number: null,
    name: null,
    idCard: null,
    mobilePhone: null,
    education: null,
    status: null,
    hireDateBegin: null,
    hireDateEnd: null,
  },
});
const add = () => {
  const window: WindowType = { name: 'EmployeeForm', component: 'EmployeeForm', label: '员工添加', icon: 'edit', width: 620, height: 750 };
  useStore.window.windowAdd(window);
};
const edit = () => {
  if (!currentRow.value) {
    ElMessage.error('请选择要修改的员工!');
    return;
  }
  const window: WindowType = {
    name: 'EmployeeForm' + currentRow.value.id,
    component: 'EmployeeForm',
    label: '员工修改（' + currentRow.value.name + '）',
    icon: 'edit',
    width: 620,
    height: 750,
    params: { id: currentRow.value.id },
  };
  useStore.window.windowAdd(window);
};
const handleTableRowClick = row => {
  currentRow.value = row;
};
const remove = () => {
  if (!currentRow.value) {
    ElMessage.error('请选择要删除的员工!');
    return;
  }
  let confirmMessage = '是否删除选中的员工?';
  // if (ids.constructor === Number) {
  //   confirmMessage = '是否删除' + name + '?';
  //   ids = [ids];
  // }

  ElMessageBox.confirm(confirmMessage, '提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(() => {
      // window.$api.module.remove(ids).then(res => {
      //   ElMessage.success('删除成功');
      //   getEmployees();
      // });
    })
    .catch(() => {});
};
const query = (): void => {
  organizationLoading.value = true;
  window.$api.organization.query({}).then(res => {
    organizations.value = res.data;
    if (!currentRow.value) {
      handleNodeClick(organizations.value[0]);
    }
    organizationLoading.value = false;
  });
};
const getEmployees = (): void => {
  loading.value = true;
  if (daterange.value) {
    params.query.hireDateBegin = daterange.value[0];
    params.query.hireDateEnd = daterange.value[1];
  }
  window.$api.employee.query(params).then(res => {
    employees.value = res.data.list;
    params.pageIndex = res.data.pageIndex;
    params.pageSize = res.data.pageSize;
    totalCount.value = res.data.totalCount;
    loading.value = false;
  });
};
const handleNodeClick = data => {
  params.query.organizationId = data.id;
  nextTick(() => {
    getEmployees();
    treeRef.value.setCurrentKey(data.id);
  });
};

const menus = reactive([
  {
    label: '修改',
    icon: 'Edit',
    fn: () => {
      edit();
    },
    license: LicenseEnum.SYS_EMPLOYEE_MODIFY,
  },
  {
    label: '删除',
    icon: 'Delete',
    fn: () => {
      remove();
    },
    license: LicenseEnum.SYS_EMPLOYEE_REMOVE,
  },
]);
const showMouseMenu = (row, column, event) => {
  const ctx = CustomMouseMenu({
    el: event.currentTarget,
    mouse: event,
    ...{ menus },
  });
  ctx.show();
  currentRow.value = row;
  tableRef.value.setCurrentRow(row);
};
onMounted(() => {
  query();
});
</script>

<template>
  <windows-window :window="window" show-searcher>
    <template #button>
      <windows-button-group size="18">
        <windows-button icon="CirclePlus" :license="LicenseEnum.SYS_EMPLOYEE_ADD" @click="add">新建</windows-button>
        <windows-button icon="Edit" :license="LicenseEnum.SYS_EMPLOYEE_MODIFY" split @click="edit"></windows-button>
        <windows-button icon="Delete" :license="LicenseEnum.SYS_EMPLOYEE_REMOVE"></windows-button>
      </windows-button-group>
    </template>
    <template #mainleft>
      <el-tree
        ref="treeRef"
        node-key="id"
        :data="organizations"
        :props="{
          children: 'children',
          label: 'name',
        }"
        default-expand-all
        highlight-current
        :expand-on-click-node="false"
        @node-click="handleNodeClick"
        v-loading="organizationLoading"
      />
    </template>
    <template #search>
      <el-form ref="form" :model="params.query" label-width="auto" label-position="right" size="small">
        <el-row>
          <el-col :span="8">
            <el-form-item label="员工工号">
              <el-input v-model="params.query.number" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="员工姓名">
              <el-input v-model="params.query.name" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="身份证号">
              <el-input v-model="params.query.idCard" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="手机号码">
              <el-input v-model="params.query.mobilePhone" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="学历">
              <el-select v-model="params.query.education">
                <el-option v-for="item in educations" :label="item.name" :value="item.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="状态">
              <el-select v-model="params.query.status">
                <el-option v-for="item in employeeStatuss" :label="item.name" :value="item.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="16">
            <el-form-item label="入职日期">
              <el-date-picker v-model="daterange" type="daterange" range-separator="To" start-placeholder="Start date" end-placeholder="End date" format="YYYY-MM-DD" value-format="YYYY-MM-DD" />
            </el-form-item>
          </el-col>
          <el-col :span="8" style="text-align: right">
            <el-button type="primary" icon="Search" @click="getEmployees">搜索</el-button>
          </el-col>
        </el-row>
      </el-form>
    </template>
    <!-- <div>
        <el-collapse value="1" accordion>
          <el-collapse-item title="" name="1">
            <el-form ref="form" :model="params" label-width="auto" label-position="left" size="default">
              <el-form-item label="Activity name">
                <el-input v-model="params.name" />
              </el-form-item>
            </el-form>
          </el-collapse-item>
        </el-collapse>
      </div> -->
    <el-table
      :data="employees"
      style="width: 100%"
      height="100%"
      row-key="Id"
      ref="tableRef"
      highlight-current-row
      default-expand-all
      @row-contextmenu="showMouseMenu"
      @row-click="handleTableRowClick"
      v-loading="loading"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column type="index" width="80" label="序号" align="center" />
      <el-table-column prop="number" label="工号" align="center"></el-table-column>
      <el-table-column prop="name" label="姓名" align="left" width="80">
        <template #default="scope">
          <span>{{ scope.row.name }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="idCard" label="身份证号" align="left" width="160">
        <template #default="scope">
          <span>{{ scope.row.idCard }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="OrganizationNames" label="所属组织机构" min-width="250" align="center">
        <template #default="scope">
          <div>
            <span v-for="item in scope.row.organizationNames">{{ item }}</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="userName" label="关联用户账号" align="center" minWidth="150">
        <template #default="scope">
          <span>{{ scope.row.userName }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="genderName" label="性别" align="center" width="80"></el-table-column>
      <el-table-column prop="status" label="状态" align="center" width="80">
        <template #default="scope">
          <el-tag type="danger" effect="dark">{{ useStore.dictionary.getComboBoxItemName('employeestatus', scope.row.status) }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="marriage" label="是否已婚" align="center">
        <template #default="scope">
          <el-switch v-model="scope.row.marriage" inline-prompt active-text="是" inactive-text="否" disabled />
        </template>
      </el-table-column>
      <el-table-column prop="education" label="文凭" align="center">
        <template #default="scope">
          <el-tag type="warning" effect="dark">{{ useStore.dictionary.getComboBoxItemName('education', scope.row.education) }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="mobilePhone" label="手机号码" align="center" width="120">
        <template #default="scope">
          <span>{{ scope.row.mobilePhone }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="email" label="邮箱" align="center" width="200">
        <template #default="scope">
          <span>{{ scope.row.email }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="address" label="地址" align="center" width="200" show-overflow-tooltip>
        <template #default="scope">
          <span>{{ scope.row.address }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="hireDate" label="入职日期" width="150"></el-table-column>
      <el-table-column prop="termDate" label="离职日期" width="150"></el-table-column>
      <el-table-column prop="avatar" label="头像" align="center"></el-table-column>
      <el-table-column prop="remark" label="备注" align="center">
        <template #default="scope">
          <span>{{ scope.row.Remark }}</span>
        </template>
      </el-table-column>
      <!-- <el-table-column prop="createdOn" label="创建日期" width="150" align="center"></el-table-column>
      <el-table-column prop="createdByName" label="创建人" width="100" align="center"></el-table-column>
      <el-table-column prop="updatedOn" label="更新日期" width="150" align="center"></el-table-column>
      <el-table-column prop="updatedByName" label="更新人" align="center"></el-table-column> -->
    </el-table>
    <template #pagination>
      <el-pagination
        v-model:currentPage="params.pageIndex"
        v-model:page-size="params.pageSize"
        :page-sizes="[20, 30, 40, 50]"
        :small="true"
        layout="total, sizes, prev, pager, next, jumper"
        :total="totalCount"
      />
    </template>
  </windows-window>
</template>

<style scoped lang="scss">
.btngroup {
  height: 50px;
  display: flex;
  align-items: center;
  .el-icon {
    font-size: 18px;
    color: #909399;
    margin-right: 15px;
  }
}
.el-tree {
  width: 180px;
}
</style>
